<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row>
        <el-col >
          <el-button type="primary" @click="showAddDialog">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表渲染 -->
      <el-table :data="rolesList" border stripe >
        <el-table-column type="expand" width='35px'>
          <template v-slot='scoped'>
            <el-row  :class="['bdbottm','vcenter',
            index1 ==0? 'bdtop':'']" v-for="(item1, index1) in scoped.row.children" 
            :key="item1.id"
            
            >
            <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag type=""
                 @close="removeRightByid(scoped.row, item1.id)" closable
                >{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 -->
              <el-col :span="19">
                <el-row :class="['vcenter' ,index2 == 0? '':'bdtop']"
                 v-for="(item2, index2) in item1.children" :key='item2.id'
                 >
                  <el-col :span="6">
                    <el-tag type="success"
                     @close="removeRightByid(scoped.row, item2.id)" closable
                    >{{item2.authName}}</el-tag>
                     <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                     <el-tag type="warning" v-for="(item3) in item2.children" :key='item3.id' 
                     @close="removeRightByid(scoped.row, item3.id)" closable >
                       {{item3.authName}}
                     </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" ></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="角色操作" width="300px">
          <template v-slot='scoped'>
               <el-tooltip
              :enterable="false"
              class="item"
              effect="dark"
              content="编辑角色"
              placement="top"
            >
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="showEditUser(scoped.row.id)"
              >编辑</el-button>
            </el-tooltip>
            <el-tooltip
              :enterable="false"
              class="item"
              effect="dark"
              content="删除用户"
              placement="top"
            >
              <el-button
                @click="removeUserById(scoped.row.id)"
                size="mini"
                type="danger"
                icon="el-icon-delete"
              >删除</el-button>
            </el-tooltip>
            <el-tooltip
              :enterable="false"
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-setting"
                @click="showSetRightDialog(scoped.row)"
              >分配权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加用户的对话框 -->
      <el-dialog
        @close="closeAddDialog"
        title="添加角色"
        :visible.sync="addUserVisible"
        width="50%"
       >
       <el-form :model="addUserInfo" label-width="80px" ref="addUserRef" :rules="addUserRules">
         <el-form-item label="角色名称" prop="roleName">
           <el-input v-model="addUserInfo.roleName" placeholder=""></el-input>
         </el-form-item>
         <el-form-item label="角色描述" prop="roleDesc">
           <el-input v-model="addUserInfo.roleDesc" placeholder=""></el-input>
         </el-form-item>
       </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑用户对话框 -->
       <el-dialog
        @close="closeEditDialog"
        title="编辑角色"
        :visible.sync="editUserVisible"
        width="50%"
       >
       <el-form :model="editForm" label-width="80px" ref="editUserRef" :rules="addUserRules">
         <el-form-item label="角色名称" prop="roleName">
           <el-input v-model="editForm.roleName" placeholder=""></el-input>
         </el-form-item>
         <el-form-item label="角色描述" prop="roleDesc">
           <el-input v-model="editForm.roleDesc" placeholder=""></el-input>
         </el-form-item>
       </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editUserVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
    <!-- 分配用户权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisable"
      width="50%"
      @close="setRightDialogClose"
      >
      <!-- 树型控件 -->
      <el-tree :data="rightsList" :props="treeProps" ref='treeRef'
      show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys"
       ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisable = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
 
<script>
export default {
  name: "Roles",
  components: {

  },
  created() {
    this.getUserList()
  },
  data () {
   return {
     //分配权限对话框显示隐藏状态
     setRightDialogVisable: false,
    // 所有权限的数据树型
    rightsList: [],
    // 树型控件的绑定对象
    treeProps: {
      label: 'authName',
      children: 'children'
    },
    // 树型默认选中的id值
    defKeys: [116, 105],
    // 当前分配权限的角色id
    roleId: '',
    editForm: {},
    rolesList: [],
    addUserVisible: false,
    editUserVisible: false,
    addUserInfo: {
       roleName: '',
       roleDesc: ''
    },
    addUserRules: {
      roleName: [
            { required: true, message: '请输入用户名称', trigger: 'blur' },
            { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
          ],
      roleDesc: [
            { required: false, message: '请输入角色描述', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
    }
   }
  },
   methods:{
     //获取用户列表数据
     async getUserList() {
       const { data: res} = await this.$request('roles')
       if(res.meta.status !== 200) return this.$message.error('获取角色列表失败')
       this.rolesList = res.data
     },
    //  显示添加角色对话框
     showAddDialog() {
       this.addUserVisible = !this.addUserVisible
     },
     //添加角色
      addUser() {
       this.$refs.addUserRef.validate( async vaild => {
         if(!vaild) return this.$message.error('信息有误，请重新输入')
          const {data : res} = await this.$request({
          url: 'roles',
          method: 'post',
          data: this.addUserInfo
       })
          console.log(res);
          if(res.meta.status !== 201) return this.$message.error('创建角色失败')
          this.getUserList()
      })
     },
     //关闭对话框事件
     closeAddDialog() {
      this.$refs.addUserRef.resetFields();
     },
      //显示编辑用户对话框
      async showEditUser(id) {
        this.editUserVisible = !this.editUserVisible
        const {data: res} = await this.$request(`roles/${id}`)
        this.editForm = res.data
      },
     //编辑用户数据
      editUser() {
         this.$refs.editUserRef.validate( async vaild => {
         if(!vaild) return this.$message.error('信息有误，请重新输入')
          const {data : res} = await this.$request({
          url: `roles/${(this.editForm.roleId)}`,
          method: 'put',
          data: this.editForm
       })
          if(res.meta.status !== 200) return this.$message.error('修改数据失败')
          this.$message.success('修改数据成功')
          this.editUserVisible = false
          this.getUserList()
      })
     },
     //关对话框
      closeEditDialog() {
       this.$refs.editUserRef.resetFields();
     },
     //删除用户的弹出框
    async removeUserById(id) {
      try {
        const res = await this.$confirm('此操作将永久删除该用户, 确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        const { data: deleteResult } = await this.$request({
          url: `roles/${id}`,
          method: 'delete'
        })
        if(deleteResult.meta.status !== 200) return this.$message.error('删除用户失败')
        this.getUserList()
        this.$message.success('已删除成功')
      } catch(err) {
        return this.$message.info('已取消删除')
      }
    },
    //根据id删除权限
    async removeRightByid(role, rightId) {
       try {
        //  messageBox弹框提示是否删除
        const confirmRes = await this.$confirm('此操作将永久删除该权限, 确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
     
        const { data: res } = await this.$request({
          url: `roles/${role.id}/rights/${rightId}`,
          method: 'delete'
        })
        role.children = res.data
        if(res.meta.status !== 200) return this.$message.error('删除用户失败')
        this.$message.success('已删除成功')
      } catch(err) {
        return this.$message.info('已取消删除')
      }
    },
    // 显示分配权限的对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取所有权限的数据
      const { data: res } = await this.$request({
          url: `rights/tree`
        })
      this.defKeys = []
      if(res.meta.status !== 200) return this.$message.error('获取权限数据失败')
      this.rightsList = res.data
      
      // 递归获取角色下所有三级权限id
      this.getLeafKeys(role, this.defKeys)  
      this.setRightDialogVisable = true;
    },
    // 递归获取角色下所有三级权限id,保存到defKey中
    getLeafKeys(node, arr) {
      // 不包含children就是三级节点
      if(!node.children) return arr.push(node.id)
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      }); 
    },
    setRightDialogClose() {
      this.defKeys = []
    },
    //点击分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
       const { data: res } = await this.$request({
         method: 'post',
          url: `roles/${this.roleId}/rights`,
          data: { rids: idStr }
        })
        console.log(res);
      if(res.meta.status !== 200) return this.$message.error('分配权限失败')
      this.$message.success('分配成功')
      this.getUserList()
      this.setRightDialogVisable = false
    }
   }
}
</script>
 
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottm {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>